package com.jk.controller;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @author yzf
 * @version 1.0
 * @ClassName test
 * @program: yzf-test
 * @description: TODO
 * @date 2025/3/19 15:56
 */
public class test {
    // yzf TODO 2025/3/19:  加密解密

//    public static void main(String[] args) {
//        String s = Base64.getEncoder().encodeToString("123".getBytes());
//        System.out.println("加密"+s);
//
//        byte[] decode = Base64.getDecoder().decode(s);
//        String s1 = new String(decode);
//        System.out.println("解密"+s1);
//    }
    // 生成密钥
    public static SecretKey generateKey(int n) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(n);
        SecretKey secretKey = keyGen.generateKey();
        return secretKey;
    }

    // 将SecretKey转换为字符串形式
    public static String encodeKey(SecretKey key) {
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }

    // 从字符串恢复SecretKey
    public static SecretKey decodeKey(String encodedKey) {
        byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
        return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
    }

    // 加密
    public static String encrypt(String plainText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密
    public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        // 生成密钥
        SecretKey key = generateKey(256); // 可以选择128, 192或256位
        System.out.println("密钥: " + encodeKey(key));

        // 加密
        String encryptedMessage = encrypt("123", key);
        System.out.println("加密后的消息: " + encryptedMessage);

        // 解密
        String decryptedMessage = decrypt(encryptedMessage, key);
        System.out.println("解密后的消息: " + decryptedMessage);
    }





}
